<link rel="stylesheet" type="text/css" href="<?= base_url() ?>file/js/easyui/themes/gray/easyui.css">
<link rel="stylesheet" type="text/css" href="<?= base_url() ?>file/js/easyui/themes/icon.css">
<script type="text/javascript" src="<?= base_url() ?>file/js/easyui/jquery.easyui.min.js"></script>

<!--dialog-->
<link rel="stylesheet" href="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/themes/ui-lightness/jquery.ui.all.css">
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/jquery-1.7.1.js"></script>
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.ui.core.js"></script>
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.ui.widget.js"></script>
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.ui.mouse.js"></script>
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.ui.button.js"></script>
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.ui.draggable.js"></script>
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.ui.position.js"></script>
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.ui.resizable.js"></script>
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.ui.dialog.js"></script>
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.effects.core.js"></script>

<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.ui.autocomplete.js" type="text/javascript"></script>
<script src="<?= base_url() ?>file/js/jquery-ui-1.8.17.custom/development-bundle/ui/jquery.ui.datepicker.js"></script>


<style>
	.ui-autocomplete
	{
		max-height: 100px;
		overflow-y: auto;
		
		overflow-x: hidden;
		padding-right: 20px;
	}

</style>



<?php
    #### tampilkan alert jika terdapat kesalahan dalam memasukkan data
	$msg = $this->session->flashdata('message');
	$salah = validation_errors();
	if($salah <> ""){
			echo'<div id="box-messages">
					<div class="messages">
							<div id="message-error" class="message message-error">
									<div class="image">
											<img src="'. base_url() .'file/shell/smooth/resources/images/icons/error.png" alt="Error" height="32" />
									</div>
									<div class="text">
											<h6>Terdapat kesalahan dalam memasukkan data:</h6>
											<br />
											<span>'. validation_errors() .'</span>
									</div>
									<div class="dismiss">
											<a href="#message-error"></a>
									</div>
							</div>
					</div>
			</div>';
	}		
	else if($msg <> ""){
		echo'<div id="box-messages">
					<div class="messages">
							 <div id="message-error" class="message message-error">
									 <div class="image">
											<img src="'. base_url() .'file/shell/smooth/resources/images/icons/error.png" alt="Error" height="32" />
									</div>
									<div class="text">
											<h6>'. $msg .'</h6>
									</div>
									<div class="dismiss">
											<a href="#message-error"></a>
									</div>
							</div>
					</div>
			</div>';
	}
?>

<form id="form" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">		
<div class="panel-wrap" style="height: auto">
	
	<div class="panel-header-div">Informasi Teritori</div>
	
    <div class="panel-body-div">
        <div class="left-panel-body">
            <h2><?=$ter_name?></h2>
        </div>
        <div class="right-panel-body">
            <table class="table-right-panel" width="100%" border="solid black 1px">
                <tr align="center" class="tr-colour">
                    <th width="50%" align="center">Tanggal</th>
                    <th align="center">Nota Pengambilan Baru</th>
                </tr>
                
                <script type="text/javascript">
				        $(function() {
							$("#date").datepicker({ 
								dateFormat: 'yy-mm-dd',
								showOn: 'button',
								buttonImageOnly: true, 
								minDate: 1, maxDate: "+1D",
								buttonImage: '<?= base_url() ?>file/js/easyui/themes/pepper-grinder/images/datebox_arrow.png' 
							});
				        });
				</script>
                <tr align="center" class="gray">
                    <td width="50%" align="center">
						<input size="15%"  type="text" id="date" name="scan_date" onclick="this.value='';" 
							value="<?php 
								date_default_timezone_set("Asia/Jakarta");
								echo date("Y-m-d");
							?>"/>
					</td>                    
					<td class="readonly" align="center" >
						<span style="font-size: 16pt"><b>Penomoran Otomatis</b></span>
					</td> 
                </tr>
            </table>
        </div>
    </div>
</div>


<script type="text/javascript">
var test = 2;
var hasSalesId = false;
var decreaser = 0;
var total = 0;
var tempIccid = "";


/** 
/* non-aktifkan submit button setelah diklik
/* @author : alfin akhret <alfin.akhret@gmail.com>
*/
$('#simpan_btn').mouseup(function(){
      $(this).attr('disabled');
    })
    .blur(function(){
      $(this).removeAttr('disabled');
    });

/**--------------------------------**/

function cekHasSalesId() {
	if (hasSalesId == false) {	
		alert("Isi nama sales terlebih dahulu!");
		return false;
	}
}

function processSalesId() {
	$('#bodyTable').empty();
	$("#subtotal").val("");
	$("#textSubtotal").val("");
	
	if ($('select#sales_id option:selected').attr('class') != "") {
		$("#sales_name").val($('select#sales_id option:selected').attr('class'));
		hasSalesId = true;
		
		// Begitu Sales Id telah ditentukan dengan click pada combo box, 
		// ambil "Limit maksimal" dan "Jumlah Belanja (current limit)"		
		getCreditLimit(); getCurrentLimit();

	}
	else {
		$("#sales_name").val($('select#sales_id option:selected').attr('class'));
		hasSalesId = false;
	}	
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2 + ",00";
}


//update field-field pada suatu row setelah field iccid diisi
function updateValue(soide)
{
	// var iccid = null;
	var iccid = $("#iccid_"+soide).val();
	var flag = false;
	var subtotal = 0;
	var valTemp = 0;
	// tempIccid = $("#iccid_"+soide).val();
	//anggwa@gmail.com 20120513
	var salesId = $("#sales_id").val().split(" ");
		
	$.ajax({
	//anggwa@gmail.com 20120513
	//url: "<?php echo base_url(); ?>index.php/scan/load_scan/"+iccid+"/"+$("#sales_id").val(),
		url: "<?php echo base_url(); ?>index.php/scan/load_scan/"+iccid+"/"+salesId[0],
		dataType:"json",
		success:function(data){
			$.each(data, function(i,n){
				if (n["valid"] != 1)
				{
					alert(n["messege"]);
					$("#iccid_"+soide).val("");
					return false;
				}
				else
				{
					//alert(n["valid"] + ", " + n["icc"] + ", " + n["sal"]);
					
					$("#mdn_"+soide).val(n["mdn"]);
					$("#item_name_"+soide).val(n["item_name"]);
					$("#item_group_name_"+soide).val(n["item_group_name"]);
					_price = n["getPrice"];
					$("#price_"+soide).val(n["getPrice"]);
					$("#textPrice_"+soide).val(addCommas($("#price_"+soide).val()));
					//updateCurrentLimit(_price);
					
					var temptotal = document.getElementById("price_"+soide).value;
					if (temptotal != "")
					{
						for (var ii=2; ii<test; ii++)
						{	
							if (document.getElementById("price_"+ii) && document.getElementById("price_"+ii).value != "")
							{
								// proses perhitungan subtotal
								// subtotal += parseFloat(document.getElementById("price_"+ii).value);
								valTemp = parseFloat(document.getElementById("price_"+ii).value);
								subtotal += valTemp;
								total = subtotal ;
								$("#subtotal").val(subtotal);
								$("#textSubtotal").val(addCommas(subtotal));
								// $("#subtotal").val(subtotal)
								// batas pencarian subtotal
							}
						}
					}
					getCurrentLimit(getSales());
					compareLimit();
					flag = true;
				}
			});	
		},
		error: function(data){	
			alert(n["messege"]);
			$("#iccid_"+soide).val("");
		}
	});
	
	//assign price yang sedang diproses rownya ke dalam variable pengurang
	decreaser = document.getElementById("price_"+soide).value;
	
	//hapus isi field yang 1 row ketika field iccid dihapus.
	if (flag == false)
	{
		$("#mdn_"+soide).val("");
		$("#item_name_"+soide).val("");
		$("#item_group_name_"+soide).val("");
		$("#price_"+soide).val("");	
		$("#textPrice_"+soide).val("");
		document.getElementById("price_"+soide).onchange();
	}	
}

function thousandSeparator(n,sep) {
	var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
	sValue=n+"";
	if (sep === undefined) {sep='.';}
	while(sRegExp.test(sValue)) {
		sValue = sValue.replace(sRegExp, '$1'+sep+'$2');
	}
	return sValue;
}

//proses perhitungan subtotal
function setSubtotal(jon)
{
	// total -= decreaser;
	$("#subtotal").val(total);
	$("#textSubtotal").val(addCommas(total));
}

//ambil daftar iccid untuk ditampilkan pada textbox autocomplete
function getIccid(varTest)
{	
	// yaddis@nutech ---29/09/2012
	// take out autocomplete feature
	$("#iccid_"+varTest).keypress(function(event){
		if ( event.which == 13 ) {
			event.preventDefault();
			// alert(varTest);
			// updateValue(varTest);
			$("#iccid_"+varTest).blur();
			// $(this).blur();
		}
	});

	$("#iccid_"+varTest).blur(function(){
			// alert(varTest);
			updateValue(varTest);
	});

	event.preventDefault();
}

//cek semua checkbox
function check_all(){
    $("INPUT[type='checkbox']").attr('checked', $('#select_all').is(':checked'));
}

//delete row yang diceklis
function delete_checked(tableID) {
	try {
		var table = document.getElementById(tableID);
		var rowCount = table.rows.length;
		
		for(var i=1; i<rowCount; i++) {
			var row = table.rows[i];
			if (row.cells[0] != null)
			{
				var chkbox = row.cells[0].childNodes[0];
				if(null != chkbox && true == chkbox.checked) {
					//invoke setSubtotal method
					decreaser = row.cells[6].childNodes[0].value;

					total = total - decreaser ;
					$("#subtotal").val(total);
					$("#textSubtotal").val(addCommas(total));
					
					//decreaseCurrentLimit(decreaser);
					getCurrentLimit(getSales());

					table.deleteRow(i);
					rowCount--;
					i--;
				}
			}
			compareLimit();
		}
	}catch(e) {
		alert(e);
	}
}

$(document).ready(function() {
	//proses penambahan row
	//$('#quantityImg').keypress(function(){
	$('tr.alert').hide();
	$('#dialog-modal').hide();
	
	$("#quantity").keydown(function(event) {
	  	if ( event.which == 13 ) {
	     	event.preventDefault();

			if (cekHasSalesId() == false)
				return false;
			
			s1 = document.getElementById("quantity").value;
			
			for(jj=0;jj<s1;jj++)
			{
				
				add_tuple = "<tr align='center' id='new_tuple"+test+"' class='wide'>"+
					"<td><input type='checkbox'/></td>"+
					// "<td><input style='text-align:left;' type='text' id='iccid_"+test+"' name='iccid[]' value='' size='30%' onkeyup='updateValue("+test+")' onfocus='getIccid("+test+")' /></td>"+				
					"<td><input style='text-align:left;' type='text' id='iccid_"+test+"' name='iccid[]' value='' size='30%' onfocus='getIccid("+test+")' /></td>"+				
					"<td><input style='text-align:left;' type='text' id='mdn_"+test+"' name='mdn[]'   readonly='readonly'  size='15%' value=''/></td>"+
					"<td><input style='text-align:left;' type='text' id='item_name_"+test+"' name='item_name[]' readonly='readonly' size='50%' value=''/></td>"+
					"<td><input  style='text-align:left;' type='text' id='item_group_name_"+test+"' name='item_group_name[]' readonly='readonly' value=''/></td>"+
					"<td ><input style='text-align:right;' type='text' id='textPrice_"+test+"' name='textPrice[]' readonly='readonly' size='10%' value='' /></td>"+
					"<td ><input style='text-align:right;' type='hidden' id='price_"+test+"' name='price[]' readonly='readonly' size='10%' value='' onchange='setSubtotal("+test+")' /></td>"+
				"</tr>";
				$('#bodyTable').append(add_tuple);
				// $("#iccid_"+test+"").focus();
				test++;
			}
	   	}
		
	});	
	$('#quantityImg').click(function(){
		$("#quantity").keydown();		
	});

    //Pada saat input ICCID, jika tombol "Enter" ditekan -> doNothing
    $('#form').bind("keypress", function(e) {
        if (e.keyCode == 13) {
            return false;
       }
    });

})

// Untuk mendapatkan Limit Maksimal dari #sales_id
function getCreditLimit (salesID) {
	var salesId = $("#sales_id").val().split(" ");
	$.ajax ({
		url: "<?php echo base_url(); ?>index.php/scan/getCreditLimit/"+salesId[0],
		dataType:"json",
		success:function(data){
			$.each(data, function(credit, value) {
				$('#cLimit').val( parseFloat( value["f_get_credit_limit"] ) );
			})
		}
	})	
}

function getSales() {
	var salesId = $("#sales_id").val().split(" ");
	return salesId[0];
}

// Untuk mendapatkan Limit Pembelian saat ini yang sudah dan sedang dilakukan #sales_id
function getCurrentLimit (salesID) {
	var salesId = $("#sales_id").val().split(" ");
	$.ajax ({
		url: "<?php echo base_url(); ?>index.php/scan/getCurrentLimit/"+getSales(),
		dataType:"json",
		success:function(data){
			$.each(data, function(credit, value) {
				var currentLimit = parseFloat(value["f_get_current_limit"])
				var limitValue   = currentLimit + total;
				$('#vLimit').val(limitValue);
			})
		}
	})
}

function decreaseCurrentLimit(param) {
	// limitValue = parseFloat(getCurrentLimit());
	//$('#vLimit').val( parseFloat(getCurrentLimit()) - parseFloat(param) );
	$('#vLimit').val(getCurrentLimit (getSales()));
	//compareLimit();
}
function updateCurrentLimit(param) {
	limitValue = $('#vLimit').val();
	// limitValue = parseFloat(vLimit)+parseFloat(param);
	//$('#vLimit').val(parseFloat(limitValue)+parseFloat(param));
	$('#vLimit').val(getCurrentLimit(getSales()));
	//compareLimit();
}

function compareLimit(){
	maksLimit = $("#cLimit").val();
	if ( parseFloat($('#vLimit').val())>parseFloat(maksLimit)) {
		$('input[type="submit"]').attr("disabled", "disabled");
		// $('tr.aalert').show();
		$( "#dialog-modal" ).dialog({
			height: 140,
			modal: true
		});
	}
	else if( parseFloat($('#vLimit').val())<parseFloat(maksLimit)) {
		$('input[type="submit"]').removeAttr("disabled");;
		$('tr.alert').hide();
	};
}

</script>

<div class="panel-wrap" style="height: auto">
	<div class="panel-header-div">Informasi Pengambilan Barang</div>
    <div class="panel-body-div">
        <div class="child-panel-body">
		
			<div class="left-panel-body">
				<table class="table-right-panel" width="60%" border="solid black 1px">
					<tr align="center" class="tr-colour2">
						<th width="20%" align="center">Nama Sales</th>
						<th align="center">NIK</th>
						
					</tr>
				   
					<tr align="center" class="gray">			
						<td width="50%" align="center">					
							<select name="sales_id" id="sales_id" onchange="processSalesId()">
							<option value="">--Pilih Sales--</option>
							<?php 
								//edited by alfin akhret
								if($this->session->userdata('is_self_service') == 1)
								{ 
									foreach($salesID as $item):
										if ($item->availability == "available" && ($item->user_id == $this->session->userdata('username')))
										{					
									?>
											<option class="<?php echo $item->user_id?>" value="<?php echo $item->user_name?>"><?php echo $item->user_name?></option>
									<?php
										}
									endforeach;
								}
								else
								{
									foreach($salesID as $item):
										if ($item->availability == "available")
										{
									?>
											<option class="<?php echo $item->user_id?>" value="<?php echo $item->user_name?>"><?php echo $item->user_name?></option>
									<?php
										}
									endforeach;
								}

								?>

							</select>		
						</td>                   
						<td class="readonly" align="center"><input type="text" name="output" id="sales_name" disabled="true" class="input-readonly" /></td> 
					</tr>
					
				</table>
				<br /><br />
				<div class="form" style="margin-left:-3%;width:153%" >
					<div class="fields" >
						<div class="field" style="border-bottom:"  >
								<div class="label"  style="margin-left:2%;">
									<label for="alias">Jumlah:</label>
								</div>
								<div class="input" style="margin-left:7%;" >
									<input type="text" id="quantity" name="quantity" onkeydown="cekHasSalesId()" size="5%" />	
									<p style="padding-top: 4px;"> &nbsp; <img id="quantityImg" src="<?= base_url() ?>file/js/easyui/themes/icons/apply.png" /> Tekan tombol "Enter" </p>
								</div>
						</div>
						   
					</div>
                </div>
				
				
				
			</div>
		</div>
	

	
	
    <div class="child-panel-body" style="margin-top: 7%;">	
            <table id="table-updateable" class="table-right-panel" width="92%" style="margin-left: 19px;">
                <thead>
					<tr align="center" class="tr-colour3">
						<th style="width:3%"><input style="width:60%" id="select_all" onclick="check_all()" type="checkbox" /></th>
						<th>ICCID</th>
						<th>MDN</th>
						<th>Keterangan</th>
						<th>Grup Item</th>
						<th>Harga (Rp.)</th>
					</tr>
				</thead>
				<tbody id="bodyTable">
				</tbody>

                
            </table>
				
               <div class="summary" style="float:right;margin-right: 3%;">
                <table width="100%">
                    <tr>
                        <td>Subtotal</td>
                        <td><input type="text" id="textSubtotal" name="subtotal" disabled="disabled"/></td>
                        <td><input type="hidden" id="subtotal" name="subtotal" disabled="disabled"/></td>
                    </tr>
<!--                     <tr class="alert">
                    	<td colspan="3">Melebihi batas pembelian</td>
                    </tr> -->
                </table>
            </div>
            
			<div class="buttons" style="margin-top:8%;">					
				<input type="button" onclick="delete_checked('table-updateable')" value="Hapus" />
				<input type="hidden" id="vLimit">
				<input type="hidden" id="cLimit">
			</div>
        
    </div>
       
        <div class="child-panel-body-2">
        
            <div class="buttons-2" style="margin: 0 auto">
                <input type="submit" value="Simpan" id="simpan_btn"/>
                <a href="javascript:history.go(0)"><input type="button" value="Reset" /></a>
            </div>
		</div>
		
    </div>
</div>
</form>


<div id="dialog-modal" title="Over buying">
	<p>Anda melebihi quota pembelian yang sudah ditentukan. </p>
</div>